import { HttpError, toSuccess, useEntityManager, useRedis } from "@sker/core";
import { KsLiveRoom, KsLiveRoomLog } from "@sker/entities";
import { useData } from "@sker/runtime";
import dayjs from "dayjs";

import { z } from "zod";
/**
 * 记录中奖 情况/参与情况
 */
export default async () => {
    const input = z.object({
        uuid: z.string(),
        room_id: z.number(), // log id
        open_time: z.string(),
        user_id: z.string(),
        money_v: z.optional(z.any()),
        red_id: z.number(),
        pkg: z.string()
    });
    const body = input.parse(useData())
    body.money_v = body.money_v || 0;
    return await useEntityManager(async (m) => {
        const room = await m.findOne(KsLiveRoom, { where: { id: body.room_id } })
        if (!room) throw new HttpError(`房间错误`)
        const old = await m.findOne(KsLiveRoomLog, { where: { uuid: body.uuid, room_id: body.room_id, red_id: body.red_id } })
        const log = m.create(KsLiveRoomLog, { id: old?.id, pkg: body.pkg, uuid: body.uuid, room_id: body.room_id, user_id: body.user_id, open_time: new Date(body.open_time), money_v: body.money_v, red_id: body.red_id });
        const { id } = await m.save(KsLiveRoomLog, log)
        await m.update(KsLiveRoom, body.room_id, { in_room_count: room.in_room_count + 1 })

        await useRedis(8, async r => {
            const key = `red.${body.uuid}`
            const value = await r.get(key)
            if (value) {
                const json = JSON.parse(value)
                if (body.pkg === `com.smile.gifmaker`) {
                    await r.set(key, JSON.stringify({
                        ...json,
                        join: json.join + 1,
                        ksJoin: json.ksJoin + 1
                    }))
                } else {
                    await r.set(key, JSON.stringify({
                        ...json,
                        join: json.join + 1,
                        jsJoin: json.jsJoin + 1
                    }))
                }
                const endDate = dayjs().endOf('day').toDate().getTime()
                const expirationTime = Math.floor((endDate - new Date().getTime()) / 1000)
                await r.expire(key, expirationTime);
            }
        })
        return toSuccess({ id })
    });
}
